//
//  AliyunOSSImageUploader.m
//  GLGW_Shoping
//
//  Created by yang on 2018/12/14.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "AliyunOSSImageUploader.h"
#import <AliyunOSSiOS/OSSService.h>

//需要的一些基本信息
static NSString *const AccessKey = @"LTAIOB0B0AbxmG73";
static NSString *const SecretKey = @"WMO2E5LWSYyOLvX8waNr6IrGZhZwVS";
static NSString *const BucketName = @"glgw-oss";
static NSString *const AliYunHost = @"http://oss-cn-huhehaote.aliyuncs.com";
static NSString *kTempFolder = @"http://oss-cn-huhehaote.aliyuncs.com";

@interface AliyunOSSImageUploader ()

@end

@implementation AliyunOSSImageUploader

+ (void)asyncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{
    [self uploadImages:@[image] isAsync:YES complete:complete];
}

+ (void)syncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{
    [self uploadImages:@[image] isAsync:NO complete:complete];
}

+ (void)asyncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    [self uploadImages:images isAsync:YES complete:complete];
}

+ (void)syncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    [self uploadImages:images isAsync:NO complete:complete];
}

+ (void)uploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete{
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey                                                                                                            secretKey:SecretKey];
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = images.count;
    
    NSMutableArray *callBackNames = [NSMutableArray array];
    int i = 0;
    for (UIImage *image in images) {
        if (image) {
            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                //任务执行
                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                put.bucketName = BucketName;
                
                //文件路径及名称拼接
                NSString *imageName = [NSString stringWithFormat:@"%@",[NSString randomStringWithLength:8]];
                NSString *suffix = [NSString stringWithFormat:@"-%zdx%zd.jpg", (NSInteger)image.size.width,(NSInteger)image.size.height];
                imageName = [imageName stringByAppendingString:suffix];
                NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", kTempFolder,imageName];
                put.objectKey = imageUrl;
                put.contentType = @"image/jpeg";
                //添加到数组回传
                [callBackNames addObject:imageUrl];
                
                //上传date
                NSData *data = UIImageJPEGRepresentation(image, 0.3);
                put.uploadingData = data;
                // 阻塞直到上传完成
                OSSTask * putTask = [client putObject:put];
                [putTask waitUntilFinished];
                if (!putTask.error) {
                    NSLog(@"upload object success!");
                } else {
                    NSLog(@"upload object failed, error: %@" , putTask.error);
                }
                if (isAsync) {
                    if (image == images.lastObject) {
                        NSLog(@"upload object finished!");
                        if (complete) {
                            complete([NSArray arrayWithArray:callBackNames] ,UploadImageSuccess);
                        }
                    }
                }
            }];
            if (queue.operations.count != 0) {
                [operation addDependency:queue.operations.lastObject];
            }
            [queue addOperation:operation];
        }
        i++;
    }
    if (!isAsync) {
        [queue waitUntilAllOperationsAreFinished];
        NSLog(@"haha");
        if (complete) {
            if (complete) {
                complete([NSArray arrayWithArray:callBackNames], UploadImageSuccess);
            }
        }
    }
#pragma mark --- sts
//    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKey secretKeyId:SecretKey securityToken:@"OSSAuth.securityToken"];
//
//    OSSClient *client = [[OSSClient alloc] initWithEndpoint:BucketName credentialProvider:credential];
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//    queue.maxConcurrentOperationCount = images.count;
//
//    NSMutableArray *callBackNames = [NSMutableArray array];
//
//    int i = 0;
//    for (UIImage *image in images) {
//        if (image) {
//            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
//                //任务执行
//                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
//                put.bucketName = BucketName;
//
//                NSString *imageName = [NSString stringWithFormat:@"%@",[NSString randomStringWithLength:8]];
//                NSString *suffix = [NSString stringWithFormat:@"-%zdx%zd.png", (NSInteger)image.size.width,(NSInteger)image.size.height];
//                imageName = [imageName stringByAppendingString:suffix];
//
//                put.objectKey = imageName;
//
//                // 传出url
//                NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", kTempFolder,imageName];
//
//                [callBackNames addObject:imageUrl];
//
//                NSData *data = UIImageJPEGRepresentation(image, 0.5);
//                put.uploadingData = data;
//
//                OSSTask * putTask = [client putObject:put];
//                [putTask waitUntilFinished]; // 阻塞直到上传完成
//
//                if (!putTask.error) {
//                    DLog(@"upload object success! \nimageUrl:%@\n", imageUrl);
//                } else {
//                    DLog(@"upload object failed, error: %@" , putTask.error);
//                }
//                if (isAsync) {
//                    if (image == images.lastObject) {
//                        NSLog(@"upload object finished!");
//                        if (complete) {
//                            complete([callBackNames copy],UploadImageSuccess);
//                        };
//                    };
//                };
//            }];
//            if (queue.operations.count != 0) {
//                [operation addDependency:queue.operations.lastObject];
//            }
//            [queue addOperation:operation];
//        }
//        i++;
//    }
//    if (!isAsync) {
//        [queue waitUntilAllOperationsAreFinished];
//        if (complete) {
//            complete([callBackNames copy],UploadImageFailed);
//        };
//    }
}


@end
